import copy
from config import SECTIONS_CONFIG

class SectionManager:
    def __init__(self, canvas, text_manager):
        self.canvas = canvas
        self.text_manager = text_manager
        self.sections = copy.deepcopy(SECTIONS_CONFIG)
        self.section_selection_mode = False
        self.selected_section = None
        
        # 创建区段点击处理器
        self._create_section_click_handler()
        self._create_sections()
    
    def _create_section_click_handler(self):
        """创建区段点击处理器"""
        def create_section_click_handler(section_name):
            return lambda event: self.on_section_click(section_name)
        self.create_section_click_handler = create_section_click_handler
    
    def _create_sections(self):
        """创建区段文本和点击区域"""
        for section_name, section_info in self.sections.items():
            x, y = section_info['text_pos']
            # 创建文本
            text_id = self.canvas.create_text(x, y, text=section_name, font=("黑体", 12), fill="black")
            # 创建可点击的矩形区域
            rect_id = self.canvas.create_rectangle(x-20, y-10, x+20, y+10, outline="", fill="", tags=f"section_{section_name}")
            # 绑定点击事件
            self.canvas.tag_bind(f"section_{section_name}", "<Button-1>", self.create_section_click_handler(section_name))
    
    def on_section_click(self, section_name):
        """区段点击事件处理函数"""
        if self.section_selection_mode:
            self.selected_section = section_name
            text_to_insert = [
                f"已选择区段: {section_name}",
                "请点击'设置区段占用'或'取消区段占用'按钮"
            ]
            self.text_manager.insert_text_with_delay(text_to_insert)
            # 高亮显示选中的区段
            self.highlight_selected_section(section_name)
        else:
            text_to_insert = [
                f"点击了区段: {section_name}",
                "请先点击'设置区段占用'按钮进入选择模式"
            ]
            self.text_manager.insert_text_with_delay(text_to_insert)

    def highlight_selected_section(self, section_name):
        """高亮显示选中的区段"""
        # 清除之前的高亮
        self.canvas.delete("section_highlight")
        # 为选中的区段添加高亮边框
        section_info = self.sections[section_name]
        x, y = section_info['text_pos']
        self.canvas.create_rectangle(x-25, y-15, x+25, y+15, outline="blue", width=2, tags="section_highlight")

    def set_section_occupancy(self, section_name):
        """设置区段占用"""
        if section_name and section_name in self.sections:
            section_info = self.sections[section_name]
            if not section_info['occupied']:
                # 创建红色线段表示占用
                coords = section_info['coords']
                red_line = self.canvas.create_line(coords[0], coords[1], coords[2], coords[3], 
                                                width=3, fill="red", smooth=True)
                section_info['red_line'] = red_line
                section_info['occupied'] = True
                text_to_insert = [
                    f"{section_name}区段被占用！"
                ]
                self.text_manager.insert_text_with_delay(text_to_insert)
            else:
                text_to_insert = [
                    f"{section_name}区段已经被占用！"
                ]
                self.text_manager.insert_text_with_delay(text_to_insert)

    def cancel_section_occupancy(self, section_name):
        """取消区段占用"""
        if section_name and section_name in self.sections:
            section_info = self.sections[section_name]
            if section_info['occupied']:
                # 删除红色线段
                if section_info['red_line']:
                    self.canvas.delete(section_info['red_line'])
                    section_info['red_line'] = None
                section_info['occupied'] = False
                text_to_insert = [
                    f"成功取消{section_name}区段占用！"
                ]
                self.text_manager.insert_text_with_delay(text_to_insert)
            else:
                text_to_insert = [
                    f"{section_name}区段未被占用！"
                ]
                self.text_manager.insert_text_with_delay(text_to_insert)

    def enter_selection_mode(self, mode_type="set"):
        """进入区段选择模式"""
        if not self.section_selection_mode:
            self.section_selection_mode = True
            self.selected_section = None
            mode_text = "设置占用" if mode_type == "set" else "取消占用"
            text_to_insert = [
                f"已进入区段选择模式",
                f"请点击要{mode_text}的区段"
            ]
            self.text_manager.insert_text_with_delay(text_to_insert)
            # 高亮所有可选择的区段
            for section_name in self.sections.keys():
                section_info = self.sections[section_name]
                x, y = section_info['text_pos']
                self.canvas.create_rectangle(x-20, y-10, x+20, y+10, outline="green", width=1, tags="selection_highlight")
        else:
            if self.selected_section:
                if mode_type == "set":
                    self.set_section_occupancy(self.selected_section)
                else:
                    self.cancel_section_occupancy(self.selected_section)
                # 退出选择模式
                self.exit_selection_mode()
            else:
                text_to_insert = [
                    "请先选择一个区段"
                ]
                self.text_manager.insert_text_with_delay(text_to_insert)

    def exit_selection_mode(self):
        """退出区段选择模式"""
        self.section_selection_mode = False
        self.selected_section = None
        self.canvas.delete("selection_highlight")
        self.canvas.delete("section_highlight")
        text_to_insert = [
            "已退出区段选择模式"
        ]
        self.text_manager.insert_text_with_delay(text_to_insert)
    
    def is_section_occupied(self, section_name):
        """检查区段是否被占用"""
        if section_name in self.sections:
            return self.sections[section_name]['occupied']
        return False 